var log4js = require('log4js');
var http = require('http');
var fs= require('fs');
var path= require('path');
var mime= require('mime');
var io = require('socket.io-client');
var mysql = require('mysql');
var express = require('express');
var app = express();

//*********************************************
// DB
//*********************************************
var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'root',
      password : 'Bc3f99ZzUgh4',
      database : "btc-watch",
      multipleStatements: true
    });
var cache = {};

log4js.configure({
    appenders: [
        {
            type: "file",
            filename: "server.log",
            category: [ 'server','console' ]
        },
        {
            type: "console"
        }
    ],
    replaceConsole: true
});


//*********************************************
// LOGGER
//*********************************************
var logger = log4js.getLogger('server');


//*********************************************
// APP start
//*********************************************
app.get('/', function(req, res){
  res.send('hello world');
});

app.get('/list', function(req, res){
    //var query = connection.query('SELECT COUNT(*) as asks FROM ASK; SELECT COUNT(*) as bids FROM BID');
    connection.query('SELECT COUNT(*) as asks FROM ask; SELECT COUNT(*) as bids FROM bid', function(err, results) {
      if (err) throw err;

      // `results` is an array with one element for every statement in the query:
      var result_1 = results[0];
      var result_2 = results[1];

      var asks = result_1[0].asks;
      var bids = result_2[0].bids;

      logger.debug("RESULTS: " + JSON.stringify(results));
      logger.debug("ASKS: " + asks);
      logger.debug("BIDS: " + bids);
      res.send("#asks: "+ asks + " / #bids " + bids);
    });
    //var result = "RESULTS: ";
    //query
    //  .on('fields', function(fields, index) {
    //    logger.debug("INDEX: " + index + " FIELDS: " + JSON.stringify(fields));
    //  })
    //  .on('result', function(row, index) {
    //    switch(index)
    //    {
    //    case 0:
    //        logger.debug("ASKS: " + row.asks);
    //        result += " ASKS: " + row.asks;
    //      break;
    //    case 1:
    //        logger.debug("BIDS: " + row.bids);
    //        result += " BIS: " + row.bids;
    //        res.send(result);
    //      break;
    //    default:
    //        logger.debug("NO RESULT...");
    //    }
    //  });


    });

app.listen(3000);

//*********************************************
// socket id
//*********************************************
var socket = io.connect('https://socketio.mtgox.com/mtgox?Currency=USD');
socket.on("connect", function(){
    logger.debug("connected to mtgox...");
    socket.emit('message', {
            channel:"dbf1dee9-4f2e-4a08-8cb7-748919a71b21",
            op:"private",
            origin:"broadcast",
            private:"trade",
        });
});

socket.on("message", function(data){
    if (data.op == 'private'){
        if(data && data.depth && data.depth.type_str == 'ask'){
            //logger.debug("Incoming ASK: " + data.depth.price + " " + data.depth.currency );
            saveAskToDB(data.depth.price);
        }
        if(data && data.depth && data.depth.type_str == 'bid'){
            //logger.debug("Incoming BID: " + data.depth.price + " " + data.depth.currency );
            saveBidToDB(data.depth.price);
        }
    }
});

//*********************************************
// Query methods
//*********************************************


function saveAskToDB(ask){
    connection.query('INSERT INTO ask (value, currency) values ('+ask+', 1)', function(err) {
      if (err) throw err;
    });
}

function saveBidToDB(bid){
    connection.query('INSERT INTO bid (value, currency) values ('+bid+', 1)', function(err) {
      if (err) throw err;
    });
}